<?php
namespace Maowenke\WorkerManTask;
class AsynchronousTaskProducer
{
    public static $address = '127.0.0.1:19345';
    public static function send(array $data,$Processing,$key=''){
        if(empty($Processing)){
            return false;
        }
        if(is_string($Processing)){
            $obj = \app($Processing);
            if(!method_exists($obj,'fire')){
                return false;
            }
        }elseif(is_object($Processing)){
            if(!method_exists($Processing,'fire')){
                return false;
            }
        }else{
            if(!is_callable($Processing)){
                return false;
            }
        }
        if (!empty($key)){
            $key_list = 'AsynchronousTaskProducer';
            $cache = \think\facade\Cache::get($key_list);
            if(empty($cache)){
                \think\facade\Cache::set($key_list,[$key]);
            }else{
                if(in_array($key,$cache)){
                    return false;
                }
                \think\facade\Cache::push($key_list,$key);
            }
            $data['AsynchronousTaskProducerKey'] = $key;

        }

        $data['Processing'] = $Processing;
        $gateway_buffer = json_encode($data);
        $client         = stream_socket_client("tcp://".self::$address, $errno, $errmsg, 10, STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
        if(strlen($gateway_buffer) == stream_socket_sendto($client, $gateway_buffer)){
            return true;
        }else{
            return false;
        }
    }
}